import { create } from 'zustand'

import {
  scheduleCalendarApiUrl,
  scheduleCommentCreateApiUrl,
  scheduleCreateApiUrl,
  scheduleDeleteApiUrl,
  scheduleDetailApiUrl,
  scheduleListApiUrl,
  scheduleStatisticsApiUrl,
  scheduleUpdateApiUrl,
  scheduleUpdateStatusApiUrl
} from '../services/apis'
import http from '../services/base'
import type {
  CreateSchedule,
  ScheduleCalendarData,
  ScheduleDetail,
  ScheduleItem,
  ScheduleList,
  ScheduleStatistics,
  UpdateSchedule,
  UpdateScheduleStatus
} from '../types'

// 日程store的类型定义
export type ScheduleStore = {
  scheduleList: ScheduleItem[] // 日程列表
  currentSchedule: ScheduleDetail | null // 当前日程详情
  loading: boolean // 加载状态
  page: number // 当前页
  pageSize: number // 每页大小
  total: number // 总条数
  status: string // 状态筛选
  keyword: string // 关键词搜索
  executorIds: string[] // 执行人筛选
  date: string // 日期筛选
  statistics: ScheduleStatistics | null // 统计数据
  statisticsLoading: boolean // 统计加载状态
  statisticsCacheTime: number | null // 统计缓存时间戳
  statisticsNextUpdateTime: Date | null // 下次更新时间
  statisticsUpdateTime: Date | null // 统计数据的更新时间
  calendarData: ScheduleCalendarData | null // 日历数据
  calendarLoading: boolean // 日历加载状态
  calendarRange: { startDate: string; endDate: string } | null // 日历查询区间

  // 方法
  fetchScheduleList: (params?: ScheduleList) => Promise<void>
  handleSearch: (params: Partial<ScheduleList>) => void
  resetSearch: () => void
  handlePageChange: (page: number, pageSize?: number) => void
  fetchScheduleDetail: (id: string) => Promise<void>
  createSchedule: (data: CreateSchedule) => Promise<boolean>
  updateSchedule: (data: UpdateSchedule) => Promise<boolean>
  updateScheduleStatus: (data: UpdateScheduleStatus) => Promise<boolean>
  deleteSchedule: (id: string) => Promise<boolean>
  addComment: (scheduleId: string, content: string) => Promise<boolean>
  clearCurrentSchedule: () => void
  fetchStatistics: (force?: boolean) => Promise<void> // 获取统计数据
  fetchCalendarData: (startDate: string, endDate: string) => Promise<void> // 获取日历数据
  setCalendarRange: (range: { startDate: string; endDate: string }) => void
  fetchCalendar: () => Promise<void>
  setDate: (date: string) => void // 设置日期筛选
}

// 日程store实现
export const useScheduleStore = create<ScheduleStore>((set, get) => ({
  scheduleList: [],
  currentSchedule: null,
  loading: false,
  page: 1,
  pageSize: 10,
  total: 0,
  status: '',
  keyword: '',
  executorIds: [],
  date: '',
  statistics: null,
  statisticsLoading: false,
  statisticsCacheTime: null,
  statisticsNextUpdateTime: null,
  statisticsUpdateTime: null,
  calendarData: null,
  calendarLoading: false,
  calendarRange: null,

  // 获取日程列表
  async fetchScheduleList(params) {
    set({ loading: true })
    try {
      const state = get()
      const searchParams = params || {
        page: state.page,
        pageSize: state.pageSize,
        status: state.status,
        keyword: state.keyword,
        executorIds: state.executorIds,
        date: state.date
      }
      const res = await http.post<ScheduleItem[]>(scheduleListApiUrl, searchParams)
      set({ scheduleList: res.data, total: res.data.length })
    } finally {
      set({ loading: false })
    }
  },

  // 设置日期筛选
  setDate: (date: string) => {
    set({ date })
  },

  // 处理搜索
  handleSearch: (params: Partial<ScheduleList>) => {
    const state = get()
    const newParams = {
      page: 1, // 搜索时重置到第一页
      pageSize: state.pageSize,
      status: params.status !== undefined ? params.status : state.status,
      keyword: params.keyword !== undefined ? params.keyword : state.keyword,
      executorIds: params.executorIds !== undefined ? params.executorIds : state.executorIds,
      date: params.date !== undefined ? params.date : state.date
    }
    set(newParams)
    get().fetchScheduleList(newParams)
  },

  // 重置搜索
  resetSearch: () => {
    const state = get()
    const resetParams = {
      page: 1,
      pageSize: state.pageSize,
      status: '',
      keyword: '',
      executorIds: [],
      date: ''
    }
    set(resetParams)
    get().fetchScheduleList(resetParams)
  },

  // 处理分页变化
  handlePageChange: (page: number, pageSize?: number) => {
    const state = get()
    const updates: { page: number; pageSize?: number } = { page }
    if (pageSize !== undefined) {
      updates.pageSize = pageSize
    }
    set(updates)
    get().fetchScheduleList({
      page,
      pageSize: pageSize || state.pageSize,
      status: state.status,
      keyword: state.keyword,
      executorIds: state.executorIds,
      date: state.date
    })
  },

  // 获取日程详情
  async fetchScheduleDetail(id) {
    set({ loading: true })
    try {
      const res = await http.post<ScheduleDetail>(scheduleDetailApiUrl, { id })
      set({ currentSchedule: res.data })
    } finally {
      set({ loading: false })
    }
  },

  // 创建日程
  async createSchedule(data) {
    set({ loading: true })
    try {
      await http.post(scheduleCreateApiUrl, data)
      return true
    } catch {
      return false
    } finally {
      set({ loading: false })
    }
  },

  // 更新日程状态
  async updateScheduleStatus(data) {
    set({ loading: true })
    try {
      await http.post(scheduleUpdateStatusApiUrl, data)
      return true
    } catch {
      return false
    } finally {
      set({ loading: false })
    }
  },

  // 更新日程（仅编辑标题）
  async updateSchedule(data) {
    set({ loading: true })
    try {
      await http.post(scheduleUpdateApiUrl, data)
      return true
    } catch {
      return false
    } finally {
      set({ loading: false })
    }
  },

  // 删除日程（方案A：自动处理分页逻辑）
  async deleteSchedule(id) {
    set({ loading: true })
    try {
      await http.post(scheduleDeleteApiUrl, { id })

      // 方案A核心逻辑：自动处理分页
      const state = get()
      const currentList = state.scheduleList
      const currentPage = state.page

      // 如果删除的是当前页最后一条且不是第一页，返回上一页
      if (currentList.length === 1 && currentPage > 1) {
        set({ page: currentPage - 1 })
        await get().fetchScheduleList()
      } else {
        // 否则刷新当前页
        await get().fetchScheduleList()
      }

      return true
    } catch {
      return false
    } finally {
      set({ loading: false })
    }
  },

  // 添加回复
  async addComment(scheduleId, content) {
    set({ loading: true })
    try {
      await http.post(scheduleCommentCreateApiUrl, { scheduleId, content })
      return true
    } catch {
      return false
    } finally {
      set({ loading: false })
    }
  },

  // 清除当前日程
  clearCurrentSchedule() {
    set({ currentSchedule: null })
  },

  // 获取统计数据
  async fetchStatistics(force = false) {
    const state = useScheduleStore.getState()
    const now = Date.now()
    const CACHE_DURATION = 10 * 60 * 1000 // 10分钟缓存

    // 检查缓存是否有效
    if (
      !force &&
      state.statistics &&
      state.statisticsCacheTime &&
      now - state.statisticsCacheTime < CACHE_DURATION
    ) {
      // 缓存有效，计算下次更新时间
      const nextUpdateTime = new Date(state.statisticsCacheTime + CACHE_DURATION)
      set({ statisticsNextUpdateTime: nextUpdateTime })
      return
    }

    // 需要请求新数据
    set({ statisticsLoading: true })
    try {
      const res = await http.post<ScheduleStatistics>(scheduleStatisticsApiUrl, {})
      const cacheTime = Date.now()
      const updateTime = new Date()
      const nextUpdateTime = new Date(cacheTime + CACHE_DURATION)

      set({
        statistics: res.data,
        statisticsCacheTime: cacheTime,
        statisticsNextUpdateTime: nextUpdateTime,
        statisticsUpdateTime: updateTime
      })
    } catch (error) {
      console.error('获取统计数据失败:', error)
    } finally {
      set({ statisticsLoading: false })
    }
  },

  // 获取日历数据
  async fetchCalendarData(startDate: string, endDate: string) {
    set({ calendarLoading: true })
    try {
      const res = await http.post<ScheduleCalendarData>(scheduleCalendarApiUrl, {
        startDate,
        endDate
      })
      set({
        calendarData: res.data,
        calendarLoading: false
      })
    } catch (error) {
      console.error('获取日历数据失败:', error)
      set({ calendarLoading: false })
    }
  },

  // 设置日历查询区间
  setCalendarRange(range) {
    set({ calendarRange: range })
  },

  // 使用最近设置的区间刷新日历数据
  async fetchCalendar() {
    const state = get()
    if (!state.calendarRange) return
    const { startDate, endDate } = state.calendarRange
    await get().fetchCalendarData(startDate, endDate)
  }
}))
